#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       untitled.py
#       
#       Copyright 2011 Jeffrey Simpson <jeffrey@isolaptop>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#       

import sys, glob, os, atpy, math, modelatm, param_finder_modules
tbl_overall = atpy.Table('/home/jeffrey/PHD/isooctane/data/NGC6752/Carreta2007.vot')
params_found = open('temp_iterator_6752.out','w')
params_found.write("LEID,JmK,VmK_TCS,Vmag,BmV,temp_VmK,temp_BmV,FeH_me_best\n")
for i in range(len(tbl_overall)):
	LEID=tbl_overall.data['ID'][i]
	Vmag=tbl_overall.data['Vmag'][i]
	Bmag=tbl_overall.data['Bmag'][i]
	FeH_me=-1.49999
	BmV=(Bmag-Vmag)-0.04 #This is done after the step above else you are doubly correcting
	Vmag=Vmag-0.12 #This is the A(V)
	if BmV!=BmV:
		continue
	else:
		J_2MASS=tbl_overall.data['Jmag'][i]
		K_2MASS=tbl_overall.data['Kmag'][i]
		#The A(V) is unapplied since the 2MASS photometry has not been corrected
		[JmK,VmK_TCS]=param_finder_modules.TCS_transforms_unfixed(J_2MASS,K_2MASS,Vmag+0.12,0.11,0)
	
	FeH_me_best=0.0
	temp_diff_best=1000.0
	for FeH_me in range(-150,250):
		FeH_me=float(FeH_me)/-100
		temp_VmK=param_finder_modules.Alonso_VmK(VmK_TCS,FeH_me)
		temp_BmV=param_finder_modules.Alonso_BmV(BmV,FeH_me)
		if temp_BmV=="" or temp_VmK=="":
			continue
		temp_diff=abs(temp_VmK-temp_BmV)
		if temp_diff_best>temp_diff:
			temp_diff_best=temp_diff
			FeH_me_best=FeH_me
	temp_VmK=param_finder_modules.Alonso_VmK(VmK_TCS,FeH_me_best)
	temp_BmV=param_finder_modules.Alonso_BmV(BmV,FeH_me_best)
	

	params_found.write(str(LEID)+','+str(JmK)+','+str(VmK_TCS)+','+str(Vmag)+','+str(BmV)+','+str(temp_VmK)+','+str(temp_BmV)+','+str(FeH_me_best)+'\n')
	
	
